<template>
  <div class="address-page">
    <header-nav />
    
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>您的账户</el-breadcrumb-item>
        <el-breadcrumb-item>收货地址</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="main-content">
      <!-- 统一导航菜单 -->
      <user-nav-menu active-menu="address" />

      <div class="address-container">
        <!-- 地址列表 -->
        <div class="address-grid">
          <!-- 添加新地址卡片 -->
          <div class="address-card new-address" @click="showAddressDialog = true">
            <el-icon class="plus-icon"><Plus /></el-icon>
            <span>新增地址</span>
          </div>

          <!-- 已有地址卡片 -->
          <div v-for="address in addresses" :key="address.id" class="address-card">
            <div class="address-header">
              <span class="name">{{ address.name }}</span>
              <span class="phone">{{ address.phone }}</span>
            </div>
            <div class="address-content">
              <p>{{ address.address }}</p>
              <p>{{ address.city }}, {{ address.province }} {{ address.postcode }}</p>
            </div>
            <div class="address-actions">
              <el-button type="primary" text @click="handleEdit(address)">编辑</el-button>
              <el-button type="danger" text @click="handleDelete(address.id)">删除</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 地址编辑对话框 -->
    <el-dialog 
      v-model="showAddressDialog" 
      :title="editingAddress ? '编辑地址' : '新增地址'"
      width="500px"
    >
      <el-form 
        ref="addressFormRef"
        :model="addressForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="收件人" prop="name">
          <el-input v-model="addressForm.name" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addressForm.phone" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="addressForm.province" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="addressForm.city" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addressForm.address" type="textarea" />
        </el-form-item>
        <el-form-item label="邮编" prop="postcode">
          <el-input v-model="addressForm.postcode" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddressDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveAddress">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import HeaderNav from '../components/HeaderNav.vue'
import UserNavMenu from '../components/UserNavMenu.vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from '../utils/axios'

const router = useRouter()
const addresses = ref([])
const showAddressDialog = ref(false)
const editingAddress = ref(null)
const addressFormRef = ref(null)

const addressForm = ref({
  name: '',
  phone: '',
  province: '',
  city: '',
  address: '',
  postcode: ''
})

const rules = {
  name: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  postcode: [{ required: true, message: '请输入邮编', trigger: 'blur' }]
}

const fetchAddresses = async () => {
  try {
    const { data } = await axios.get('/api/addresses')
    addresses.value = data
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取地址列表失败')
  }
}

const handleMenuSelect = (key) => {
  switch(key) {
    case 'orders':
      router.push('/orders')
      break
    case 'address':
      router.push('/address')
      break
    case 'wishlist':
      router.push('/wishlist')
      break
    case 'recent':
      router.push('/recent-views')
      break
    case 'details':
      router.push('/profile')
      break
  }
}

const handleEdit = (address) => {
  editingAddress.value = address
  addressForm.value = { ...address }
  showAddressDialog.value = true
}

const handleDelete = async (id) => {
  try {
    await axios.delete(`/api/addresses/${id}`)
    ElMessage.success('删除成功')
    await fetchAddresses()
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('删除失败')
  }
}

const handleSaveAddress = async () => {
  if (!addressFormRef.value) return
  
  await addressFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (editingAddress.value) {
          await axios.put(`/api/addresses/${editingAddress.value.id}`, addressForm.value)
        } else {
          await axios.post('/api/addresses', addressForm.value)
        }
        
        ElMessage.success(editingAddress.value ? '更新成功' : '添加成功')
        showAddressDialog.value = false
        await fetchAddresses()
      } catch (error) {
        console.error('Error:', error)
        ElMessage.error(editingAddress.value ? '更新失败' : '添加失败')
      }
    }
  })
}

onMounted(() => {
  fetchAddresses()
})
</script>

<style scoped>
.address-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.breadcrumb {
  max-width: 1400px;
  margin: 20px auto;
  padding: 0 20px;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.address-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.address-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.address-card {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  position: relative;
}

.new-address {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 1px dashed #dcdfe6;
  min-height: 180px;
}

.new-address:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.plus-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.address-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.name {
  font-weight: bold;
}

.phone {
  color: #666;
}

.address-content {
  color: #666;
  line-height: 1.5;
}

.address-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .address-grid {
    grid-template-columns: 1fr;
  }
}
</style> 